<?php
/**
 * Created by PhpStorm.
 * User: C。
 * Date: 2019/8/13
 * Time: 9:04
 */
namespace app\home\controller;

use app\common\model\Order as OrderModel;
use app\common\model\OrderRefund as OrderRefundModel;
use app\common\model\Goods as GoodsModel;
use app\common\model\GoodsGroup as GoodsGroupModel;
use app\common\model\GoodsGroupPerson as GoodsGroupPersonModel;
use app\common\model\GoodsIlike as GoodsIlikeModel;
use app\common\model\GoodsOption as GoodsOptionModel;

/**
 * Order 商品评论控制器
 * Class Order
 * @package app\home\controller
 */
class Order extends Base
{
    /**
     * [getIndex  获取订单]
     * @return json
     * @param type 1待付款 2已付款 3已完成 4已关闭 5全部订单
     * @author [C。]
     */
    public function getIndex()
    {
        $param = input('param.');
        $model = new OrderModel;
        $rmodel = new OrderRefundModel;
        $this->getPageAndSize($param);
        $map = [];
        $map1 = [];
        $user = $this->user;
        try{
            if($param['type'] == 1){
                $map['o.status'] = 0;
                $time = time() - 15*60;
                $map['o.create_time'] = ['gt',$time];
            }elseif($param['type'] == 2){
                $map['o.status'] = 1;
                $day = strtotime(date('Y-m-d'));
                $map['o.gotime'] = ['egt',$day];
            }elseif($param['type'] == 3){
                $map['o.status'] = 1;
                $day = strtotime(date('Y-m-d'));
                $map['o.gotime'] = ['lt',$day];
            }elseif($param['type'] == 4){
                $map['o.status'] = 0;
                $time = time() - 15*60;
                $map['o.create_time'] = ['elt',$time];
                $map1['o.status'] = 2;
            }
            $map['o.memid'] = $user['id'];
            $field = 'o.id,o.create_time,o.status,o.price,o.gotime,g.title,g.cover,go.person_num,go.day,go.marketprice,o.num,o.refundid,o.type';
            if($param['type'] == 4){
                $count = $model->getCounts($map,$map1);//满足条件的总数
                $allpage = intval(ceil($count / $this->size));//总页数
                $lists = $model->getlists($map,$map1,$this->from, $this->size,$field);
            }else {
                $count = $model->getCount($map);//满足条件的总数
                $allpage = intval(ceil($count / $this->size));//总页数
                $lists = $model->getlist($map, $this->from, $this->size, $field);
            }
            foreach($lists as &$v){
                if($v['status'] == 0){
                    $time = time() - 15*60;
                    if(strtotime($v['create_time']) > $time){
                        $v['state'] = '待付款';
                    }
                    if(strtotime($v['create_time']) <= $time){
                        $v['state'] = '已关闭';
                    }
                }
                if($v['status'] == 1){
                    $day = strtotime(date('Y-m-d'));
                    if($v['gotime'] >= $day){
                        $v['state'] = '已付款';
                    }
                    if($v['gotime'] < $day){
                        $v['state'] = '已完成';
                    }
                }
                if($v['status'] == 2){
                    $v['state'] = '已关闭';
                }
                if(!empty($v['refundid'])){
                    $refund = $rmodel->findData($v['refundid'],'id','status,create_time,refund_time');
                    if($refund['status'] == 0){
                        $v['state'] = '退款审核中';
                    }elseif($refund['status'] == 1){
                        $v['state'] = '通过退款审核';
                    }elseif($refund['status'] == 2){
                        $v['state'] = '退款拒绝';
                    }
                }
                $v['cover'] = explode(',',$v['cover']);
                $v['cover'] = $v['cover'][0];
                $v['gotime'] = date('Y-m-d',$v['gotime']);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1,'获取成功',[
            'count' => $count,//总记录数
            'allpage' => $allpage,  //总页数
            'lists' => $lists,  //列表数据
        ]);
    }
    /**
     * [getContent  获取订单详情]
     * @return json
     * @author [C。]
     */
    public function getDetial()
    {
        $param = input('param.');
        $model = new OrderModel();
        $gimodel = new GoodsIlikeModel;
        $map = [];
        $memid = $this->user;
        try{
            $map['o.id'] = $param['id'];
            $field = 'o.id,o.create_time,o.ordersn,o.price,o.num,o.name,o.tel,o.status,o.people,o.gotime,o.paytime,o.paytype,o.close_time,o.update_time,g.title,g.cover,go.person_num,go.day,go.marketprice,g.notice,o.refundid,o.type,g.cancel_policy';
            $detial = $model->getOne($map,$field);
            $ilike = $gimodel->findOne(['goodsid'=>$param['id'],'memid'=>$memid['id'],'status'=>1]);
            if(!empty($ilike)){
                $detial['ilike'] = 1;
            }else{
                $detial['ilike'] = 2;
            }
            if($detial['status'] == 0){
                $time = time() - 15*60;
                if(strtotime($detial['create_time']) > $time){
                    $detial['state'] = '待付款';
                    $detial['status'] = 0;
                }
                if(strtotime($detial['create_time']) <= $time){
                    $detial['state'] = '已关闭';
                    $detial['status'] = 2;
                    $time = strtotime($detial['create_time']) + 3600 * 12;
                    if(empty($detial['close_time'])){
                        $detial['close_time'] = $time;
                    }
                }
            }
            if($detial['status'] == 1){
                $day = strtotime(date('Y-m-d'));
                if($detial['gotime'] >= $day){
                    $detial['state'] = '已付款';
                    $detial['status'] = 1;
                }
                if($detial['gotime'] < $day){
                    $detial['state'] = '已完成';
                    $detial['status'] = 3;
                }
            }
            if($detial['status'] == 2){
                $detial['state'] = '已关闭';
            }
            if(!empty($detial['refundid'])){
                $rmodel = new OrderRefundModel;
                $refund = $rmodel->findData($detial['refundid'],'id','status,create_time,refund_time');
                if($refund['status'] == 0){
                    $detial['state'] = '退款审核中';
                    $detial['status'] = 4;
                    $detial['refund_create_time'] = $refund['create_time'];
                }elseif($refund['status'] == 1){
                    $detial['state'] = '通过退款审核';
                    $detial['status'] = 5;
                    $detial['refund_update_time'] = $refund['refund_time'];
                }elseif($refund['status'] == 2){
                    $detial['state'] = '退款拒绝';
                    $detial['status'] = 6;
                }
            }
            $detial['gotime'] = date('Y-m-d',$detial['gotime']);
            $detial['paytime'] = date('Y-m-d',$detial['paytime']);
            $detial['close_time'] = date('Y-m-d',$detial['close_time']);
            $detial['people'] = json_decode(unserialize($detial['people']));
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '获取失败'.$e->getMessage());
        }
        return admin_json(1, '获取成功',$detial);
    }
    /**
     * [getIndex  添加订单]
     * @param type 1整团 2发起拼团 3参与拼团
     * @return json
     * @author [C。]
     */
    public function postAdd()
    {
        $param = input('param.');
        $model = new OrderModel();
        $gmodel = new GoodsModel();
        $ggmodel = new GoodsGroupModel;
        $user = $this->user;
        $map = [];
        $map1 = [];

        try{
            if(!check_mobile($param['tel']))
                return admin_json(-2, '手机号错误！');
            $good = $gmodel->findData($param['goodsid'],'id','title,total');

            $map1['memid'] = $user['id'];
            $map1['status'] = 0;
            $map1['create_time'] = ['gt',time()-15*60];
            $map1['goodsid'] = $param['goodsid'];
            $order = $model->findOne($map1,'id');
            if(!empty($order)){
                return admin_json(-3, '您当前有待付款订单，请先支付。');
            }

            if($param['type'] == 1){
                $gotime = strtotime($param['gotime']);
                $time = time()-15*60;
                $groupnum1 = $model->getCount1($param['goodsid'],$gotime,$time);
                $groupnum2 = $model->getCount2($param['goodsid'],$gotime);
                $groupnum = $groupnum1[0]['num'] + $groupnum2[0]['num'];
                if($groupnum >= $good['total']){
                    return admin_json(-3, '当日订单已售完。');
                }

                if($param['num'] > $param['personnum']){
                    return admin_json(-3, '超出整团人数！');
                }
            }elseif($param['type'] == 2){
                $gotime = strtotime($param['gotime']);
                $time = time()-15*60;
                $groupnum1 = $model->getCount1($param['goodsid'],$gotime,$time);
                $groupnum2 = $model->getCount2($param['goodsid'],$gotime);
                $groupnum = $groupnum1[0]['num'] + $groupnum2[0]['num'];

                if($groupnum >= $good['total']){
                    return admin_json(-3, '当日订单已售完。');
                }

                if($param['num'] > $param['personnum']){
                    return admin_json(-3, '超出拼团人数！');
                }
                if($param['num'] == $param['personnum']){
                    $param['type'] == 1;
                }
            }elseif($param['type'] == 3){
                $group = $ggmodel->findData($param['group_id'],'id','num');
                $map['groupid'] = $param['group_id'];
                $map['status'] = 0;
                $map['create_time'] = ['gt',time()-15*60];
                $ordernum = $model->getSum($map,'num');

                $num = $param['personnum'] - $group['num'] - $ordernum;
                if($param['num'] > $num){
                    return admin_json(-3, '超出拼团人数！');
                }
                $param['groupid'] = $param['group_id'];
            }

            $param['memid'] = $user['id'];
            $param['ordersn'] = 'CL'.date('YmdHis').randString();
            $param['people'] = serialize($param['people']);
            $param['gotime'] = strtotime($param['gotime']);
            $id = $model->addData($param);
            $param['id'] = $id;

        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '添加失败'.$e->getMessage());
        }
        return admin_json(1, '添加成功',$param);
    }
    /**
     * [postEdit  修改订单]
     * @param type 1整团 2发起拼团 3参与拼团
     * @return json
     * @author [C。]
     */
    public function postEdit()
    {
        $param = input('param.');
        $model = new OrderModel;
        $opmodel = new GoodsOptionModel;
        $ggmodel = new GoodsGroupModel();
        try{
            $order = $model->findData($param['id'],'id','memid,optionid,goodsid,type,num,groupid,gotime');
            $option = $opmodel->findData($order['optionid'],'id','person_num');
            if($order['type'] == 2){
                $gpmodel = new GoodsGroupPersonModel();
                $data = array(
                    'gotime' => $order['gotime'],
                    'addtime' => time(),
                    'num' => $order['num'],
                    'orderid' => $param['id']
                );
                $id = $ggmodel->addData($data);
                $data1 = array(
                    'group_id'=>$id,
                    'memid'=>$order['memid'],
                    'addtime'=>time(),
                    'orderid'=>$param['id']
                );
                $gpmodel->addData($data1);
                $model->editData(['id'=>$param['id'],'status'=>1,'paytype'=>$param['paytype'],'paytime'=>time(),'groupid'=>$id]);
            }elseif($order['type'] == 3){
                $gpmodel = new GoodsGroupPersonModel();
                $data = [];
                $group = $ggmodel->findData($order['groupid'],'id','num');
                $num = $group['num'] + $order['num'];
                $data = array(
                    'id'=>$order['groupid'],
                    'num'=>$num,
                );
                if($num >= $option['person_num']){
                    $data['status'] = 2;
                }
                $ggmodel->editData($data);
                $data1 = array(
                    'group_id'=>$order['groupid'],
                    'memid'=>$order['memid'],
                    'addtime'=>time(),
                    'orderid'=>$param['id']
                );
                $gpmodel->addData($data1);
                $model->editData(['id'=>$param['id'],'status'=>1,'paytype'=>$param['paytype'],'paytime'=>time()]);
            }elseif($order['type'] == 1){
                $model->editData(['id'=>$param['id'],'status'=>1,'paytype'=>$param['paytype'],'paytime'=>time()]);
            }
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [postEdit  修改订单]
     * @return json
     * @author [C。]
     */
    public function postStatus()
    {
        $param = input('param.');
        $model = new OrderModel;
        try {
            if($param['status'] == 2){
                $param['close_time'] = time();
            }
            $model->editData($param);
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '修改失败'.$e->getMessage());
        }
        return admin_json(1, '修改成功');
    }
    /**
     * [postAppPay  微信APP支付]
     * @param  paytype 1微信app支付 2微信公众号支付 11支付宝app支付
     * @return json
     * @author [C。]
     */
    public function getAppPay()
    {
        $param = input('param.');
        $model = new OrderModel;
        $gmodel = new GoodsModel;
        $ggmodel = new GoodsGroupModel();
        $gpmodel = new GoodsOptionModel();

        $mch_id = config('home.fmch_id');  //商户号
        $key = config('home.fmch_secret');//商户密钥
        $order = $model->findData($param['id'],'id','price,ordersn,type,groupid,num,goodsid,gotime,optionid');
        $option = $gpmodel->findData($order['optionid'],'id','person_num');

        $good = $gmodel->findData($order['goodsid'],'id','title,total');
        if($order['type'] == 1 || $order['type'] == 2){
            $gotime = $order['gotime'];
            $time = time()-15*60;
            $groupnum1 = $model->getCount1($order['goodsid'],$gotime,$time);
            $groupnum2 = $model->getCount2($order['goodsid'],$gotime);
            $groupnum = $groupnum1[0]['num'] + $groupnum2[0]['num'];

            if($groupnum > $good['total']){
                return admin_json(-3, '当日订单已售完。');
            }
        }

        if($order['type'] == 3){
            if(!empty($order['groupid'])){
                $group = $ggmodel->findData($order['groupid'],'id','num');
                $map['groupid'] = $order['groupid'];
                $map['status'] = 0;
                $map['create_time'] = ['gt',time()-15*60];
                $ordernum = $model->getSum($map,'num');
                $num = $option['person_num'] - $group['num'] - $ordernum + $order['num'];
                if($order['num'] > $num){
                    return admin_json(-2, '超出拼团人数！');
                }
            }
        }

        $out_trade_no = $order['ordersn'];
        $body = '福善禅旅';
        $total_fee = floatval($order['price']*100);

        if($param['app'] == 1){
            $appid = config('home.kappid');//开放平台appid
            $trade_type = 'APP';

            $data = array();
            $data["appid"] = $appid;
            $data["mch_id"] = $mch_id;
            $data["nonce_str"] = $this->getNonceStr();
            $data["body"] = $body;
            $data["out_trade_no"] = $out_trade_no;
            $data["total_fee"] = $total_fee;
            $data["spbill_create_ip"] = $this->get_client_ip();
            $data["notify_url"] = 'http://www.fushan8.com';
            $data["trade_type"] = $trade_type;
            $response = $this->post('https://api.mch.weixin.qq.com/pay/unifiedorder', $data);
            $data = array();
            $data["appid"] = $appid;
            $data["partnerid"] = $mch_id;
            $data["noncestr"] = $this->getNonceStr();
            $data["prepayid"] = $response["prepay_id"];
            $data["package"] = 'Sign=WXPay';
            $data["timestamp"] = time();
            $data["sign"] = $this->sign($data);
            $data['id'] = $param['id'];
            return admin_json(1, '获取成功',$data);
        }elseif($param['app'] == 2){
            $appid = config('home.wappid');//公众平台appid
            $trade_type = 'JSAPI';
            $openid = new Openid(config('home.wappid'),config('home.wsecret'));
            $userinfo = $openid->auth_user();
            $openid = $userinfo['openid'];
        }

        $weixinpay = new \WeixinPay\WeixinPay($appid,$openid,$mch_id,$key,$out_trade_no,$body,$total_fee,$trade_type);
        $return = $weixinpay->pay();

        if($return){
            $return['id'] = $param['id'];
            return admin_json(1, '获取成功',$return);
        }else{
            return admin_json(-1, '获取失败');
        }
    }
    /**
     * [getCheck  微信查询订单]
     * @param
     * @return json
     * @author [C。]
     */
    public function getCheck()
    {
        $param = input('param.');
        $model = new OrderModel();
        try{
            $orderno = $model->findData($param['id'],'id','ordersn');
            if($param['app'] == 1){
                $appid = config('home.kappid');//开放平台appid
            }elseif($param['app'] == 2){
                $appid = config('home.wappid');//公众平台appid
            }
            $mch_id = config('home.fmch_id');  //商户号
            $key = config('home.fmch_secret');  //商户密钥
            $out_trade_no = $orderno['ordersn'];
            $weixinpay = new \WeixinPay\WeixinPay($appid,$openid = '',$mch_id,$key,$out_trade_no,$body = '',$total_fee = '');
            $return = $weixinpay->check();
        }catch(\Exception $e){
            systembug($e->getMessage(),2,$this->url);
            return admin_json(-1, '查询失败'.$e->getMessage());
        }
        if($return){
            if($return['return_code'] == "SUCCESS"){
                if($return['trade_state'] == 'SUCCESS'){
                    return admin_json(1, '订单支付成功');
                }else{
                    return admin_json(-1, '订单支付失败');
                }
            }else{
                return admin_json(-1, '订单支付失败');
            }
        }else{
            return admin_json(-1, '订单支付失败');
        }
    }
    private function getNonceStr() {
        return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz0123456789"), 0, 32);
    }
    private function get_client_ip() {
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        } else {
            $ip = defined('PHPUNIT_RUNNING') ? '127.0.0.1' : gethostbyname(gethostname());
        }

        return filter_var($ip, FILTER_VALIDATE_IP) ?: '127.0.0.1';
    }
    /**
     * 数据签名
     * @param $data
     * @return string
     */
    private function sign($data) {
        ksort($data);
        $string1 = "";
        foreach ($data as $k => $v) {
            if ($v && trim($v) != '') {
                $string1 .= "$k=$v&";
            }
        }
        $stringSignTemp = $string1 . "key=" . config('home.fmch_secret');
        $sign = strtoupper(md5($stringSignTemp));
        return $sign;
    }
    private function post($url, $data, $cert = false) {
        if (!isset($data['sign'])) {
            $data["sign"] = $this->sign($data);
        }

        $xml = $this->array2xml($data);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        $content = curl_exec($ch);
        $array = $this->xml2array($content);
        return $array;
    }
    private function array2xml($array) {
        $xml = "<xml>" . PHP_EOL;
        foreach ($array as $k => $v) {
            if ($v && trim($v) != '') {
                $xml .= "<$k><![CDATA[$v]]></$k>" . PHP_EOL;
            }

        }
        $xml .= "</xml>";
        return $xml;
    }
    private function xml2array($xml) {
        $array = array();
        $tmp = null;
        try
        {
            $tmp = (array) simplexml_load_string($xml);
        } catch (Exception $e) {

        }
        if ($tmp && is_array($tmp)) {
            foreach ($tmp as $k => $v) {
                $array[$k] = (string) $v;
            }
        }
        return $array;
    }
}